# -*- coding: utf-8 -*-
from typing import Annotated

from fastapi import APIRouter, Path, Depends, Query, Request
from fastapi_limiter.depends import RateLimiter

from App.app.admin.services.menu_service import MenuService
from App.common.pagination import paging_data, DependsPagination
from App.common.respones.response_schema import ResponseModel, response_base
from App.common.security.jwt import DependsJwtAuth
from App.database.mysql import CurrentSession

# 动态导入模型和Schema
from App.app.admin.services.sys_role_service import SysRoleService
from App.app.admin.schemas.sys_role_schema import (
    CreateSysRoleParam,
    UpdateSysRoleParam,
    GetSysRoleListDetails, SysRoleSchema, UpdateRoleMenuParam
)
from App.utils.serializers import select_list_serialize

router = APIRouter(prefix="/role")


@router.get('/all', summary='获取所有角色', dependencies=[Depends(RateLimiter(times=20, minutes=1)), DependsJwtAuth])
async def get_all_roles() -> ResponseModel:
    roles = await SysRoleService.get_all()
    data = select_list_serialize(roles)
    return response_base.success(data=data)


@router.get(
    '/{pk}',
    summary='根据ID获取角色详情',
    description="根据ID获取角色详情",
    dependencies=[Depends(RateLimiter(times=20, minutes=1)), DependsJwtAuth]
)
async def get_sys_role(pk: Annotated[int, Path(...)]) -> ResponseModel:
    sys_role = await SysRoleService.get(pk=pk)
    return response_base.success(data=SysRoleSchema.model_validate(sys_role))


@router.get(
    '',
    summary='（模糊条件）分页获取所有角色',
    description='（模糊条件）分页获取所有角色',
    dependencies=[
        Depends(RateLimiter(times=20, minutes=1)),
        DependsJwtAuth,
        DependsPagination
    ]
)
async def get_pagination_sys_role(db: CurrentSession,
                                  name: Annotated[str | None, Query()] = None,
                                  status: Annotated[str | None, Query()] = None) -> ResponseModel:
    """
    对于实际业务中，角色列表一般来说比较少。通过状态筛选实际意义不大，前端可以考虑不需要通过状态筛选
    :param db:
    :param name:
    :param status:
    :return:
    """
    sys_role_select = await SysRoleService.get_select(name=name, status=status)
    page_data = await paging_data(db, sys_role_select, GetSysRoleListDetails)
    return response_base.success(data=page_data)


@router.post(
    '',
    summary='创建角色',
    description='创建角色',
    dependencies=[Depends(RateLimiter(times=20, minutes=1)), DependsJwtAuth]
)
async def create_sys_role(obj_in: CreateSysRoleParam) -> ResponseModel:
    data = await SysRoleService.create(obj_in=obj_in)
    return response_base.success(data=SysRoleSchema.model_validate(data))


@router.put(
    '',
    summary='更新角色详情',
    description='更新角色详情',
    dependencies=[Depends(RateLimiter(times=20, minutes=1)), DependsJwtAuth]
)
async def update_sys_role(obj_in: UpdateSysRoleParam) -> ResponseModel:
    count = await SysRoleService.update(obj_in=obj_in)
    if count > 0:
        return response_base.success()
    return response_base.fail()


@router.delete(
    '/{pk}',
    summary='删除角色',
    description='删除角色',
    dependencies=[Depends(RateLimiter(times=20, minutes=1)), DependsJwtAuth]
)
async def delete_sys_role(pk: int = Path(...)) -> ResponseModel:
    count = await SysRoleService.delete(pk=pk)
    if count > 0:
        return response_base.success()
    return response_base.fail()


@router.get('/{pk}/menus', summary='获取角色所有菜单', dependencies=[Depends(RateLimiter(times=20, minutes=1)), DependsJwtAuth])
async def get_role_all_menus(pk: Annotated[int, Path(...)]) -> ResponseModel:
    menu = await MenuService.get_role_menu(pk=pk)
    return response_base.success(data=menu)


@router.put(
    '/menus',
    summary='更新角色菜单',
    dependencies=[Depends(RateLimiter(times=20, minutes=1)), DependsJwtAuth]
)
async def update_role_menus(
    request: Request, obj_in: UpdateRoleMenuParam
) -> ResponseModel:
    count = await SysRoleService.update_role_menu(request=request, obj_in=obj_in)
    if count > 0:
        return response_base.success()
    return response_base.fail()
